package com.api.info.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jspxcms.core.domain.Info;

/**
 * 工具类，提供转换操作
 * 
 * @author wangxiaonan@pansoft.com
 * @since 2017年10月14日
 */
public class Convert {
	public static final String SPLIT = ",";
	private static final String NOT_MATCH = "The '%s' parameter not a %s";
	private static final String REQUIRED = "The '%s' paramter is required";

	private static final String FORMAT_DATE = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 将cms中info列表转换为移动端需要的数据内容
	 * 
	 * @return
	 */
	public static JSONArray infoPage2Json(Page<Info> page) {
		JSONArray jsonPage = new JSONArray();
		SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
		for (Info info : page) {
			JSONObject rs = new JSONObject();
			// 作者信息
			rs.put("id", info.getId());
			rs.put("title", info.getTitle());
			rs.put("fullTitle", info.getFullTitle());
			rs.put("subTitle", info.getSubtitle());
			rs.put("author", info.getAuthor());
			// rs.put("creator", info.getCreator());
			rs.put("source", info.getSource());
			rs.put("publishDate", sdf.format(info.getPublishDate()));
			rs.put("keyWords", info.getKeywords());
			// rs.put("description", info.getDescription());
			// rs.put("content", info.getText());
			// 图片信息
			rs.put("withImage", info.getWithImage());
			rs.put("smallImage", info.getSmallImage());
			rs.put("largeImage", info.getLargeImage());
			rs.put("attrImage", info.getAttrImage());

			jsonPage.add(rs);
		}

		return jsonPage;
	}

	public static JSONObject info2Json(Info info) {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
		JSONObject rs = new JSONObject();
		// 作者信息
		rs.put("id", info.getId());
		rs.put("title", info.getTitle());
		rs.put("fullTitle", info.getFullTitle());
		rs.put("subTitle", info.getSubtitle());
		rs.put("author", info.getAuthor());
		rs.put("source", info.getSource());
		rs.put("publishDate", sdf.format(info.getPublishDate()));
		rs.put("content", info.getText());
		rs.put("keyWords", info.getKeywords());
		rs.put("description", info.getDescription());
		// // 图片信息
		rs.put("withImage", info.getWithImage());
		rs.put("smallImage", info.getSmallImage());
		rs.put("largeImage", info.getLargeImage());
		rs.put("attrImage", info.getAttrImage());

		return rs;
	}

	public static Integer[] getIntegers(HttpServletRequest request, String paramKey, Boolean required) {
		String text = request.getParameter(paramKey);
		if (required && StringUtils.isBlank(text)) {
			throw new NullPointerException(String.format(REQUIRED, paramKey));
		}
		if (text == null) {
			return null;
		} else if (StringUtils.isBlank(text)) {
			return new Integer[0];
		}

		String[] stringArray = StringUtils.split(text, SPLIT);
		if (ArrayUtils.isEmpty(stringArray)) {
			throw new NullPointerException(String.format(REQUIRED, paramKey));
		}
		int length = stringArray.length;
		Integer[] numberArray = new Integer[length];
		try {
			for (int i = 0; i < length; i++) {
				numberArray[i] = Integer.valueOf(stringArray[i]);
			}
			return numberArray;
		} catch (NumberFormatException e) {
			throw new NumberFormatException(String.format(NOT_MATCH, paramKey, "integer array"));
		}
	}

	public static String[] getStrings(HttpServletRequest request, String paramKey, Boolean required) {
		String text = request.getParameter(paramKey);
		String[] array = StringUtils.split(text, SPLIT);
		if (ArrayUtils.isEmpty(array) && required) {
			throw new NullPointerException(String.format(REQUIRED, paramKey));
		}
		return array;
	}

	public static Date getDate(HttpServletRequest request, String paramKey, Boolean isEndDate, Boolean required) {
		String text = request.getParameter(paramKey);
		if (StringUtils.isBlank(text)) {
			return null;
		}
		DateTime dt;
		try {
			// 将2017-05-01 18:00:00 转换为 2017-05-01T18:00:00
			Date date = new SimpleDateFormat(FORMAT_DATE).parse(text);
			dt = new DateTime(date.getTime());
			if (isEndDate && text.length() <= 10) {
				dt = dt.plusDays(1);
				dt = dt.minusMillis(1);
			}
		} catch (Exception e) {
			throw new NumberFormatException(
					String.format(NOT_MATCH, paramKey, " Illegal Date, legal format like " + FORMAT_DATE));
		}
		return dt.toDate();
	}

	public static Boolean getBoolean(HttpServletRequest request, String paramKey, Boolean defVal, Boolean required) {
		Boolean rs = defVal;
		String text = request.getParameter(paramKey);
		if (StringUtils.isNotBlank(text)) {
			rs = BooleanUtils.toBoolean(text);
		}
		if (rs == null && required) {
			throw new NullPointerException(String.format(REQUIRED, paramKey));
		}
		return rs;
	}

	/**
	 * 获取查询排序方式，默认desc
	 * 
	 * @param request
	 * @param paramKey
	 * @param required
	 * @return
	 */
	public static Direction getSortType(HttpServletRequest request, String paramKey, Boolean required) {
		String text = request.getParameter(paramKey);
		if (required && StringUtils.isBlank(text)) {
			throw new NullPointerException(String.format(REQUIRED, paramKey));
		}
		if (StringUtils.isNotBlank(text)) {
			return Direction.fromString(text);
		}

		return Direction.DESC;
	}

	/**
	 * 获取查询排序字段
	 * 
	 * @param request
	 * @param paramKey
	 * @param required
	 * @param defValue
	 *            排序字段数组
	 * @return
	 */
	public static List<String> getSortField(HttpServletRequest request, String paramKey, Boolean required,
			String[] defValue) {
		String[] fields = getStrings(request, paramKey, required);
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < defValue.length; i++) {
			list.add(defValue[i]);
		}
		if (fields == null || fields.length == 0) {
			return list;
		}
		for (String field : fields) {
			list.add(field);
		}
		return list;
	}

	/**
	 * 获取页面，前台从1开始，后台查询还是从0开始
	 * 
	 * @param request
	 * @param paramKey
	 * @param required
	 * @return
	 */
	public static int getPage(HttpServletRequest request, String paramKey, Boolean required) {
		int page = 1;
		String text = request.getParameter(paramKey);
		if (StringUtils.isBlank(text)) {
			return page - 1;
		}
		page = Integer.parseInt(text);
		if (page < 1) {
			page = 1;
		}
		return page - 1;
	}

	/**
	 * 获取分页条数，默认值15条，最少1条
	 * 
	 * @param request
	 * @param paramKey
	 * @param required
	 * @return
	 */
	public static int getPageSize(HttpServletRequest request, String paramKey, Boolean required) {
		int page = 15;
		String text = request.getParameter(paramKey);
		if (StringUtils.isBlank(text)) {
			return page;
		}
		page = Integer.parseInt(text);
		if (page < 1) {
			page = 1;
		}
		return page;
	}

	// Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
	public static Map<String, Object> transBean2Map(Object obj) {

		if (obj == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();

				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);

					map.put(key, value);
				}

			}
		} catch (Exception e) {
			System.out.println("transBean2Map Error " + e);
		}

		return map;

	}
}
